<?php


namespace TbfRuntime\Session;


class NativeSession implements SessionProvider{
    private static $obj=null;

    static function obj(){
        if (self::$obj==null){
            self::$obj = new static();
        }
        return self::$obj;
    }
    private function __construct(){}


    /**
     * @param string $key
     * @return mixed
     */
    function get($key)
    {
        self::init();
        if (!array_key_exists($key,$_SESSION)){
            return null;
        }
        return $_SESSION[$key];
    }

    /**
     * @param string $key
     * @param mixed $value
     * @return void
     */
    function set($key, $value)
    {
        self::init();
        $_SESSION[$key] = $value;
    }

    /**
     * @return void
     */
    function regenerate()
    {
        self::init();
        session_regenerate_id(true);
        $_SESSION = array();
    }

    /**
     * @return void
     */
    function clear()
    {
        self::init();
        session_destroy();
        $_SESSION = array();
    }

    /**
     * @return array map[string]interface{}
     */
    function getAll()
    {
        self::init();
        return $_SESSION;
    }

    /**
     * @param array $array map[string]interface{}
     * @return void
     */
    function setAll($data)
    {
        self::init();
        $_SESSION = $data;
    }

    private static $hasStart=false;
    private function init(){
        if (!self::$hasStart){
            session_start();
            self::$hasStart = true;
        }
    }
} 